package ink.xiaobaibai.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.apache.commons.lang3.time.DateUtils;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @description: token工具类
 * @author: 小白白
 * @create: 2021-05-19
 **/

public class TokenUtil {

    private static final String TOKEN_ASSERT = "wq1#3^4tqr^et35a@sgzse@asg$zx1$$vs";
    private static final JWTVerifier JWTVERIFIER = JWT.require(Algorithm.HMAC256(TOKEN_ASSERT)).build();

    /**
     * 返回JWT
     *
     * @param userId
     * @return
     */
    public static String getJWT(Integer userId) {
        Date nowDate = new Date();
        return JWT.create()
                .withAudience(String.valueOf(userId))
                .withIssuedAt(nowDate)
                //失效时间 365天
                .withExpiresAt(DateUtils.addDays(nowDate, 30))
                .sign(Algorithm.HMAC256(TOKEN_ASSERT));
    }

    /**
     * 验证jwt,返回其userId
     *
     * @param jwt
     * @return
     */
    public static Integer validJWT(String jwt, HttpServletResponse response) {
        DecodedJWT decodedJWT;
        try {
            decodedJWT = JWTVERIFIER.verify(jwt);
            if (DateUtils.addDays(new Date(), 5).getTime() > decodedJWT.getExpiresAt().getTime()) {
                response.setHeader("Authorization", getJWT(Integer.parseInt(decodedJWT.getAudience().get(0))));
            }
        } catch (Exception e) {
            return null;
        }
        return Integer.parseInt(decodedJWT.getAudience().get(0));
    }

    public static void main(String[] args) {
        System.out.println(getJWT(50));
    }

}
